package com.example.common.mvvm.model;

import com.blankj.utilcode.util.NetworkUtils;
import com.example.common.entity.NetErrorEntity;
import com.example.common.fieid.NetFieldConst;
import com.example.common.entity.BaseEntity;
import com.example.common.mvvm.RxFunction;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public abstract class BaseRespository {
    //创建请求requestbody
    protected RequestBody createBody(Map<String,Object> map){
        String jsonStr=new Gson().toJson(map);
        return RequestBody.create(
                MediaType.parse("application/json;charset=UTF-8"),jsonStr);
    }

    //转化网络请求接口为BaseEntity类型
    protected Observable<BaseEntity> functionObservable(Observable observable){
        return observable.map(new RxFunction());
    }
    //合并请求
    protected Observable<BaseEntity> mergeObservable(Observable... observables){
        Observable<BaseEntity> observable=null;
        ArrayList<Observable<BaseEntity>> list=new ArrayList<>();
        //遍历可变参数->生成集合
        for (int i = 0; i < observables.length; i++) {
            list.add(functionObservable(observables[i]));
        }
        //使用合并操作符->将多个被观察者任务合并为一个被观察者任务
        observable=Observable.merge(list);
        return observable;
    }

    //检查网络
    protected Observable<BaseEntity> checkNetWork(Observable observable){
        Observable<BaseEntity>ob=null;
        //校验网络请求->无网络链接时->返回NetErrorEntity任务
        if (NetworkUtils.isConnected()){
            ob=functionObservable(observable);
        }else {
            NetErrorEntity entity=new NetErrorEntity();
            entity.status= NetFieldConst.NETERRO;
            entity.message=NetFieldConst.NETERROMSG;
            Observable<NetErrorEntity>netErrorEntityObservable=Observable.just(entity);
            ob=functionObservable(netErrorEntityObservable);
        }
        return ob;
    }


}
